# -*- coding: utf-8 -*-
from django.utils.translation import ugettext as _
from django.conf import settings
from django.http import HttpResponse, Http404, QueryDict 
from django.shortcuts import render_to_response, redirect
from django.views.generic.simple import direct_to_template
from this_site.models import *
from washing.models import *
from washing.forms import *
from washing.utils import *
from django.core.paginator import Paginator
from django.core.context_processors import csrf
from django.template import RequestContext
from django.core.paginator import Paginator
import json
from django.db.models import Q
import datetime

class json_mod:

    def __init__(self, function):
        self._f = function

    def __call__(self, *args):

        response = self._f(*args)
        return HttpResponse(json.dumps(response))#,
#                            mimetype='application/javascript')

@json_mod
def service_sum_admin(request, template=None):
    context = RequestContext(request)
    context.update(csrf(request))
    if request.method == 'POST':
        services = json.loads(request.POST['services'])
        sum = 0
        for price in Price.objects.filter(autotype=services['autotype'], service__in=services['services']):
            sum += price.sum
        if services['client'] and Client.objects.get(pk=services['client']).discount:
            sum *= 0.9
        data = {
                'status': 'ok',
                'sum': sum,
                }
        return data
    raise Http404

@json_mod
def check_free_ajax(request, template=None):
    context = RequestContext(request)
    context.update(csrf(request))
    if request.method == 'POST':
        return check_free_or_sum(int(request.POST['client']))
    raise Http404

@json_mod
def show_report_day(request, template=None):
    context = RequestContext(request)
    context.update(csrf(request))
    if request.method == 'POST':
        form = SelectDateForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data.copy()
            data = {
                    'status': 'ok',
                    'pk': report_day(cd['date']).pk,
                    }
            return data
        else: 
            pass
    raise Http404

def get_report_day(request, year, month, day, year_end=None, month_end=None, day_end=None, template=None):
    context = RequestContext(request)
    context.update(csrf(request))
    
#    context.update({
#                    })
#    
#    return render_to_response(template, context)
    if year_end and month_end and day_end:
        return report_day_xls(datetime.date(int(year), int(month), int(day)), datetime.date(int(year_end), int(month_end), int(day_end)))
    return report_day_xls(datetime.date(int(year), int(month), int(day)))